package com.api.weavernorth.createDoc;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.weavernorth.util.Logger4jUtil;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.interfaces.workflow.action.Action;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import static com.weavernorth.util.dateUtils.getYearMonthDay;

/**
 * @Author: BruseeWang
 * @Date: 2020/11/26 14:59
 * @Description:
 */
@Path("/weavernorth/cteateDoc")
public class downLoadFile extends HttpServlet {
    public static Logger log = Logger4jUtil.getLoggerByName("/action/api/createDoc/downLoadFile/");
    @POST
    @Path("/getFile")
    @Produces(MediaType.TEXT_PLAIN)
    public String getV8Message(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        BaseBean bb = new BaseBean();
        String strRequestid= Util.null2String(request.getParameter("requestid"));
        JSONObject jsonReturn =new JSONObject();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date()); //设置时间为当前时间
        cal.add(Calendar.MONTH, -1);
        String preMonth = format.format(cal.getTime());
        String year = preMonth.split("-")[0];
        String month = preMonth.split("-")[1];
        String day = preMonth.split("-")[2];
        String strNow=year+"年"+month+"月"+day+"日";
        log.info("当前年:" + year + ",月:" + month+ ",日:" + day);
        int iyear=Integer.parseInt(year);
        int nextYear=iyear+1;
        RecordSet rsTable=new RecordSet();
        JSONObject  jsonObject = new JSONObject();
        JSONArray jsonArray=new JSONArray();
        String strTable ="";
        rsTable.execute("select tablename  from workflow_bill where id = (select formid from workflow_base where id=(select workflowid from workflow_requestbase  where requestid='"+strRequestid+"') and isbill=1)");
        if(rsTable.next()){
            strTable=rsTable.getString("tablename");
        }
        String strSql="SELECT a.sqfs,a.requestid,a.TBR,a.tbsj,a.TBRBM,c.dpmc as gsmc,a.gsyyzzzch,a.sqpp,d.sapbm dpbm,d.DPMC dpmc,b.dpdz,b.sqerdos,b.sq1980,b.sqcjb,b.sqejb,b.sqblueerdos FROM "+strTable+" a inner join "+strTable+"_dt1 b on a.id=b.mainid LEFT JOIN uf_t_kna1 c ON a.GSQC1 = c.dpdm  LEFT JOIN uf_md_lc_qdxkfxsj d ON b.dpbm=d.id WHERE a.id=b.MAINID AND a.REQUESTID="+strRequestid;
//        String strSql="a.requestid,a.TBR,a.tbsj,a.TBRBM,a.gsqc1,a.gsyyzzzch,a.sqpp,b.dpbm,b.dpmc,b.dpdz,b.sqerdos,b.sq1980,b.sqcjb,b.sqejb,b.sqblueerdos FROM "+strTable+" a inner join "+strTable+"_dt1 b on a.id=b.mainid WHERE a.id=b.MAINID AND a.REQUESTID="+strRequestid;
        log.info("sql语句："+strSql);
        RecordSet rs_detail=new RecordSet();
        rs_detail.execute(strSql);
        int flag=0;
        while (rs_detail.next()){
            //店铺编码
            String strdpbm = Util.null2String(rs_detail.getString("dpbm"));
            //店铺名称
            String strdpmc = Util.null2String(rs_detail.getString("dpmc"));
            //店铺地址
            String strdpdz = Util.null2String(rs_detail.getString("dpdz"));
            //公司名称
            String strgsmc = Util.null2String(rs_detail.getString("gsmc"));
            //营业执照
            String stryyzz = Util.null2String(rs_detail.getString("gsyyzzzch"));
            //授权方式(0:单一授权；1:批量授权)
            String strSqfs = Util.null2String(rs_detail.getString("sqfs"));
            //授权书类型
            String strsqslx ="";
            String sqblueerdos = Util.null2String(rs_detail.getString("sqblueerdos"));
            String sqerdos = Util.null2String(rs_detail.getString("sqerdos"));
            String sq1980 = Util.null2String(rs_detail.getString("sq1980"));
            String sqcjb = Util.null2String(rs_detail.getString("sqcjb"));
            String sqejb = Util.null2String(rs_detail.getString("sqejb"));
            if("1".equals(strSqfs)) {
                if (sqblueerdos.equals("0")) {
                    strsqslx = "5";
                    JSONObject obj = new JSONObject();
                    obj.put("templateType", strsqslx);
                    obj.put("dpbm", strdpbm);
                    obj.put("dpmc", strdpmc);
                    obj.put("dpdz", strdpdz);
                    obj.put("gsmc", strgsmc);
                    obj.put("yyzz", stryyzz);
                    obj.put("gsmc", strgsmc);
                    obj.put("syqx_begin", iyear + "年12月1日");
                    obj.put("syqx_end", nextYear + "年11月30日");
                    obj.put("qzrq", strNow);
                    jsonArray.add(obj);
                }
                if (sqerdos.equals("0")) {
                    strsqslx = "3";
                    JSONObject obj = new JSONObject();
                    obj.put("templateType", strsqslx);
                    obj.put("dpbm", strdpbm);
                    obj.put("dpmc", strdpmc);
                    obj.put("dpdz", strdpdz);
                    obj.put("gsmc", strgsmc);
                    obj.put("yyzz", stryyzz);
                    obj.put("gsmc", strgsmc);
                    obj.put("syqx_begin", iyear + "年12月1日");
                    obj.put("syqx_end", nextYear + "年11月30日");
                    obj.put("qzrq", strNow);
                    jsonArray.add(obj);
                }
                if (sq1980.equals("0")) {
                    strsqslx = "1";
                    JSONObject obj = new JSONObject();
                    obj.put("templateType", strsqslx);
                    obj.put("dpbm", strdpbm);
                    obj.put("dpmc", strdpmc);
                    obj.put("dpdz", strdpdz);
                    obj.put("gsmc", strgsmc);
                    obj.put("yyzz", stryyzz);
                    obj.put("gsmc", strgsmc);
                    obj.put("syqx_begin", iyear + "年12月1日");
                    obj.put("syqx_end", nextYear + "年11月30日");
                    obj.put("qzrq", strNow);
                    jsonArray.add(obj);
                }
                if (sqcjb.equals("0")) {
                    strsqslx = "2";
                    JSONObject obj = new JSONObject();
                    obj.put("templateType", strsqslx);
                    obj.put("dpbm", strdpbm);
                    obj.put("dpmc", strdpmc);
                    obj.put("dpdz", strdpdz);
                    obj.put("gsmc", strgsmc);
                    obj.put("yyzz", stryyzz);
                    obj.put("gsmc", strgsmc);
                    obj.put("syqx_begin", iyear + "年12月1日");
                    obj.put("syqx_end", nextYear + "年11月30日");
                    obj.put("qzrq", strNow);
                    jsonArray.add(obj);
                }
                if (sqejb.equals("0")) {
                    strsqslx = "4";
                    JSONObject obj = new JSONObject();
                    obj.put("templateType", strsqslx);
                    obj.put("dpbm", strdpbm);
                    obj.put("dpmc", strdpmc);
                    obj.put("dpdz", strdpdz);
                    obj.put("gsmc", strgsmc);
                    obj.put("yyzz", stryyzz);
                    obj.put("gsmc", strgsmc);
                    obj.put("syqx_begin", iyear + "年12月1日");
                    obj.put("syqx_end", nextYear + "年11月30日");
                    obj.put("qzrq", strNow);
                    jsonArray.add(obj);
                }
                flag++;
            }
        }
        if(flag==0){
            strSql="SELECT a.sqslx,a.requestid,a.TBR,a.tbsj,a.TBRBM,d.sapbm dpbm,d.DPMC dpmc,a.dpdz,c.dpmc as gsmc,a.gsyyzzzch,a.sqpp FROM "+strTable+" a LEFT JOIN uf_t_kna1 c ON a.GSQC1 = c.dpdm LEFT JOIN uf_md_lc_qdxkfxsj d ON a.dpbm=d.id where a.REQUESTID="+strRequestid;
//            strSql="SELECT a.requestid,a.TBR,a.tbsj,a.TBRBM,a.gsqc1,a.dpbm,a.dpmc,a.dpdz,a.gsyyzzzch,a.sqpp FROM "+strTable+" a   where a.REQUESTID="+strRequestid;
            log.info("sql语句2："+strSql);
            RecordSet rs_main=new RecordSet();
            rs_main.execute(strSql);
            while (rs_main.next()){
                //店铺编码
                String strdpbm = Util.null2String(rs_main.getString("dpbm"));
                //店铺名称
                String strdpmc = Util.null2String(rs_main.getString("dpmc"));
                //店铺地址
                String strdpdz = Util.null2String(rs_main.getString("dpdz"));
                //公司名称
                String strgsmc = Util.null2String(rs_main.getString("gsmc"));
                //营业执照
                String stryyzz = Util.null2String(rs_main.getString("gsyyzzzch"));
                //授权书类型
                String strsqslx =Util.null2String(rs_main.getString("sqslx"));
                log.info("授权书类型"+strsqslx);
                String[] sqslx=strsqslx.split(",");
                if(sqslx.length>0){
                    for(int i=0;i<sqslx.length;i++){
                        log.info("拆分后的授权书类型,行"+i+":"+sqslx[i].toString());
                        JSONObject obj = new JSONObject();
                        obj.put("templateType",sqslx[i].toString());
                        obj.put("dpbm",strdpbm);
                        obj.put("dpmc",strdpmc);
                        obj.put("dpdz",strdpdz);
                        obj.put("gsmc",strgsmc);
                        obj.put("yyzz",stryyzz);
                        obj.put("gsmc",strgsmc);
                        obj.put("syqx_begin",iyear+"年12月1日");
                        obj.put("syqx_end",nextYear+"年11月30日");
                        obj.put("qzrq",strNow);//year+"年"+month+"月"+day+"日"
                        jsonArray.add(obj);
                    }
                }
            }
        }
        jsonObject.put("mainData",jsonArray);
        log.info("待传数据："+jsonObject.toString());
        String strUrl = com.weaver.general.Util.null2String(bb.getPropValue("createDoc", "url"));
        log.info("接口地址："+strUrl);
        String strResponse= null;
        try {
            strResponse = senDealPost(strUrl,jsonObject);
            log.info("接口响应结果："+strResponse);
            com.alibaba.fastjson.JSONObject jsonObject2 = com.alibaba.fastjson.JSONObject.parseObject(strResponse);
            String ResultCode=jsonObject2.getString("ResultCode");
            log.info("ResultCode："+ResultCode);
            String ResultMsg=jsonObject2.getString("ResultMsg");
            if(ResultMsg==null){
                ResultMsg="";
            }
            log.info("ResultMsg："+ResultMsg);
            String DownloadUrl=jsonObject2.getString("DownloadUrl");
            log.info("DownloadUrl："+DownloadUrl);
            jsonReturn.put("ResultCode",ResultCode);
            jsonReturn.put("ResultMsg",ResultMsg);
            jsonReturn.put("DownloadUrl",DownloadUrl);
        } catch (IOException e) {
            e.printStackTrace();
            jsonReturn.put("ResultCode","E");
            jsonReturn.put("ResultMsg","程序异常,异常信息"+e.toString());
            jsonReturn.put("DownloadUrl","");
            log.info("接口异常："+e.toString());
        }
        return jsonReturn.toString();
    }


    /**
     * 发送post请求,json格式
     * @param strUrl       请求路径
     * @param jsonParam     请求体
     * @return
     * @throws IOException
     */
    public static String senDealPost(String strUrl, com.alibaba.fastjson.JSONObject jsonParam) throws IOException {
        String strBody = "";
        log.info("接口地址："+strUrl);
        //创建httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();
        //创建post方式请求对象
        HttpPost httpPost = new HttpPost(strUrl);
        log.info("创建post方式请求对象");
        //装填参数
        StringEntity stringEntity = new StringEntity(jsonParam.toString(), "utf-8");
        log.info("封装参数");
        stringEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        //设置参数到请求对象中
        httpPost.setEntity(stringEntity);
        log.info("设置参数到请求对象中");
        //设置header信息
        //指定报文头【Content-type】、【User-Agent】
        httpPost.setHeader("Content-type", "application/json");
        log.info("指定报文头");
        try {
            //执行请求操作，并拿到结果（同步阻塞）
            CloseableHttpResponse response = client.execute(httpPost);
            log.info("执行请求操作，并拿到结果（同步阻塞）"+response);
            //获取结果实体
            HttpEntity entity = response.getEntity();
            log.info("获取结果实体");
            if (entity != null) {
                //按指定编码转换结果实体为String类型
                strBody = EntityUtils.toString(entity, "utf-8");
            }
            EntityUtils.consume(entity);
            //释放链接
            response.close();
        } catch (Exception e) {
            log.info("异常捕获=" + e);
        }

        return strBody;
    }

}

